var demoData = [];
for (var i = 1; i < 6; i++) {
	demoData.push({
			id:'',
			position:i,
			desc: parseInt(Math.random() * 100),
			name: 'Product ' + i,
			package_id: 4
		});
}	

function swapArrayElements(array_object, index_a, index_b) {
    var temp = array_object[index_a];
	temp.position=index_b;
	array_object[index_b].position=index_a;
    array_object[index_a] = array_object[index_b];
	array_object[index_b] = temp;
 }

 function getHtml()
 {
	var arr = demoData;
	var textToInsert = [];
	var i = 1;
	var length = arr.length;
	for (var a = 1; a <=length; a += 1) {
		textToInsert[i++] = '<tr><td><input name="inclusion_ids[]" value="'+arr[a].id+'" type="checkbox"/></td>';
		textToInsert[i++] = '<td>'+arr[a].name+'</td>';
		textToInsert[i++] = '<td class="options-width">' ;
		if(a!=length)
		textToInsert[i++] = '<a href="#'+a+'" curpos='+arr[a].position+' title="down" class="icon-6 info-tooltip"></a>' ;
		if(a!=1)
		textToInsert[i++] = '<a href="#'+a+'" curpos='+arr[a].position+' title="up" class="icon-7 info-tooltip"></a>' ;
		textToInsert[i++] = '</td></tr>';
	}
	return textToInsert;
 }

$(function() {
	$('#product-table').find("tr:gt(0)").remove();
	$('#product-table').append(getHtml().join(''));
});				

$(document).ready(function () { 
	$('.icon-6').live('click',function () { 
		var curpos= $(this).attr("curpos");
		var title=$(this).attr("title");
		if(title=='up')
		{
			var nextpos=parseInt(curpos)-1;
			swapArrayElements(demoData, parseInt(curpos), nextpos);
		}
		if(title=='down')
		{
			var nextpos=parseInt(curpos)+1;
			swapArrayElements(demoData, parseInt(curpos), nextpos);
		}
		$('#product-table').find("tr:gt(0)").remove();
		$('#product-table').append(getHtml().join(''));
	});
	$('.icon-7').live('click',function () { 
		var curpos= $(this).attr("curpos");
		var title=$(this).attr("title");
		if(title=='up')
		{
			var nextpos=parseInt(curpos)-1;
			swapArrayElements(demoData, parseInt(curpos), nextpos);
		}
		if(title=='down')
		{
			var nextpos=parseInt(curpos)+1;
			swapArrayElements(demoData, parseInt(curpos), nextpos);
		}
		$('#product-table').find("tr:gt(0)").remove();
		$('#product-table').append(getHtml().join(''));
	});
});					
